package com.ruoyi.web.controller.payment;

import com.ruoyi.common.utils.ResultMap;
import com.ruoyi.system.service.payment.WxPayService;
import com.ruoyi.web.controller.common.ClearDataJob;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

@Service
public class WxPayController {
    private static final Logger logger = LoggerFactory.getLogger(WxPayController.class);
    @Autowired
    private WxPayService wxPayService;

    /**
     * 统一下单接口
     */
    public ResultMap unifiedOrder(
            @RequestParam String orderNo,
            @RequestParam double amount,
            @RequestParam String body,
            HttpServletRequest request) {
        System.err.println("**********orderNo+\"\"+amount+\"\"+body*********"+orderNo+""+amount+""+body);
        try {
            // 1、验证订单是否存在

            // 2、开始微信支付统一下单
            ResultMap resultMap = wxPayService.unifiedOrder(orderNo, amount, body);
            return resultMap;//系统通用的返回结果集，见文章末尾
        } catch (Exception e) {
            return ResultMap.error("运行异常，请联系管理员");
        }
    }

    /**
     * 微信支付异步通知
     */
    public String payNotify(HttpServletRequest request) {
        InputStream is = null;
        String xmlBack = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[报文为空]]></return_msg></xml> ";
        try {
            is = request.getInputStream();
            // 将InputStream转换成String
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            xmlBack = wxPayService.notify(sb.toString());
        } catch (Exception e) {
            System.out.println("微信手机支付回调通知失败：" + e);
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return xmlBack;
    }


    public ResultMap refund(@ApiParam(value = "订单号") @RequestParam String orderNo,
                            @ApiParam(value = "退款金额") @RequestParam double amount,
                            @ApiParam(value = "退款原因") @RequestParam(required = false) String refundReason){
        return wxPayService.refund(orderNo, amount, refundReason);
    }




}
